import { useMemo } from 'react';
import { FacilityDevice, PowerDevice } from '../types';

/**
 * 自定义hook：处理电力设备数据
 * @param facilities 所有设施设备数据
 * @returns 过滤并格式化后的电力设备数据
 */
export const usePowerDevices = (
  facilities: FacilityDevice[]
): PowerDevice[] => {
  const powerDevices = useMemo(() => {
    return facilities
      .filter(facility => ['UPS', 'PDU', 'Transformer', 'Generator'].includes(facility.type))
      .map(facility => {
        // 类型断言确保我们可以安全访问PowerDevice特有的属性
        const device = facility as PowerDevice;
        return {
          ...device,
          // 确保status字段符合要求
          status: (device.status as 'online' | 'offline' | 'warning' | 'error') || 'offline',
          // 确保必需的字段都有值
          inputVoltage: 'inputVoltage' in device ? device.inputVoltage : 0,
          outputVoltage: 'outputVoltage' in device ? device.outputVoltage : 0,
          current: 'current' in device ? device.current : 0,
          powerRating: 'powerRating' in device ? device.powerRating : 0,
          efficiency: 'efficiency' in device ? device.efficiency : 0,
          batteryLevel: 'batteryLevel' in device ? device.batteryLevel : undefined
        };
      });
  }, [facilities]);

  return powerDevices;
};

export default usePowerDevices;